package xjtu.se.articlecommunity.common.SSE.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import xjtu.se.articlecommunity.common.CacheService;
import xjtu.se.articlecommunity.common.SSE.service.SSEService;

import javax.annotation.Resource;
import java.io.IOException;

@Service
@Transactional
public class SSEServiceImpl implements SSEService {

    @Resource
    private CacheService cacheService;

    @Override
    public void push(String id, String type) throws IOException {
        SseEmitter sseEmitter = cacheService.findMessSseEmitter(id);
        if (sseEmitter != null) {
            try {
                sseEmitter.send(type);
            } catch (IOException e) {
                push(id, type);
            }
        }
    }

    @Override
    public void over(String id) {
        SseEmitter sseEmitter = cacheService.findMessSseEmitter(id);
        if (sseEmitter != null) {
            sseEmitter.complete();
            cacheService.clearMessSseEmitter(id);
        }
    }
}
